import { ref } from 'vue';
import { useRouter } from 'vue-router';
export default function () {
  //权限列表
  let roleList: { [key: string]: any } = ref({
    read: 'R',
    write: 'W',
    delete: 'D',
    add: 'A'
  })
  let routerData = JSON.parse(localStorage.getItem('roleRoutes') as string) || []
  //当前路由信息
  let { currentRoute } = useRouter();

  //遍历得到匹配项
  function findItemByTitle(routerData: any, title: unknown): any {
    for (const item of routerData) {
      // 检查当前项的name是否与目标title相等
      if (item.name == title) {
        return item;
      }
      //如果当前项有children属性，递归查找
      if (item.children && item.children.length > 0) {
        const found = findItemByTitle(item.children, title);
        // 如果在子项中找到了匹配项，立即返回
        if (found) {
          return found;
        }
      }
    }
    // 如果遍历完没有找到匹配项，返回null
    // return {};
  }
  let { authorize, name } = findItemByTitle(routerData, currentRoute.value.meta.title) || {}
  //权限赋值
  Object.keys(roleList.value).forEach((item) => {
    if (roleList.value[item] === authorize) {
      roleList.value[item] = true
      roleList.value['read'] = true
    } else {
      roleList.value[item] = false
    }
  })
  // console.log(currentRoute.value.meta.title, '---------------' + name)
  //数组类型权限
  // let keysToModify = ['R', 'W'] as const; // 使用as const确保数组元素保持其静态类型
  // keysToModify.forEach(key => {
  //   if (key in roleList.value) {
  //     roleList.value[key] = true;
  //   }
  // });
  // console.log(roleList.value)
  return roleList
}

